package com.zcily.demo.controller;

import com.zcily.demo.entity.dto.Result;
import com.zcily.demo.entity.form.ValidateForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;

/**
 * @Validated 使用总结：
 * 1. @PathVariable @RequestParam 等参数是非对象的数据，必须在 @Controller 类上面添加 @Validated 注解（在参数上添加无效）
 * 2. 如果是参数是对象数据，对象前需要添加 @Validated 注解
 * 3. 如果是嵌套对象的数据，在字段上添加 @Valid 注解（如果是集合对象，同样需要添加 @Valid 注解）
 */
@RestController
@RequestMapping("/validate")
@Slf4j
@Validated
@Api(tags = "参数校验")
public class ValidateController {

    @ApiOperation(value = "简单的表单参数校验")
    @RequestMapping(value = "/form/simple", method = {RequestMethod.GET, RequestMethod.POST})
    public Object fromSimple(@NotNull(message = "年龄不能为空") Integer id, @Length(min = 6, max = 20, message = "用户名长度必须在{min}和{max}之间") String username) {
        return id + " :: " + username;
    }

    @ApiOperation(value = "对象表单参数校验")
    @RequestMapping(value = "/form/object", method = {RequestMethod.GET, RequestMethod.POST})
    public Object fromObject(@Validated ValidateForm form) {
        return form;
    }

    @ApiOperation(value = "json对象参数校验")
    @RequestMapping(value = "/json/object", method = {RequestMethod.POST})
    public Object jsonObject(@RequestBody @Validated ValidateForm form) {
        return form;
    }

    @ApiOperation(value = "地址栏参数校验")
    @RequestMapping(value = "/urlPath/{age}", method = {RequestMethod.GET, RequestMethod.POST})
    public Object urlPath(@PathVariable("age") @Max(value = 200, message = "年龄不能大于200岁") @NotNull(message = "年龄不能为空") Integer age) {
        return Result.ok(age);
    }
}
